import React, { useState } from 'react';
import { Modal, Form, Input, Select, Upload, message, Progress, Alert } from 'antd';
import { InboxOutlined, UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '@/services/systemManagementApi';

const { Dragger } = Upload;
const { TextArea } = Input;

interface FileUploadModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const FileUploadModal: React.FC<FileUploadModalProps> = ({ visible, onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [fileList, setFileList] = useState<any[]>([]);

  // 处理文件上传
  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择文件');
      return;
    }

    try {
      const values = await form.validateFields();
      setUploading(true);
      setUploadProgress(0);

      const formData = new FormData();
      formData.append('file', fileList[0]);
      formData.append('usage_type', values.usage_type);
      if (values.description) {
        formData.append('description', values.description);
      }

      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 200);

      const response = await uploadFile(formData);
      
      clearInterval(progressInterval);
      setUploadProgress(100);

      setTimeout(() => {
        message.success('文件上传成功');
        form.resetFields();
        setFileList([]);
        setUploadProgress(0);
        onSuccess();
      }, 500);

    } catch (error) {
      message.error('文件上传失败');
    } finally {
      setUploading(false);
    }
  };

  // 文件上传配置
  const uploadProps = {
    name: 'file',
    multiple: false,
    fileList,
    beforeUpload: (file: File) => {
      // 检查文件大小（限制为50MB）
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        message.error('文件大小不能超过50MB');
        return false;
      }

      // 检查文件类型
      const allowedTypes = [
        'image/jpeg', 'image/png', 'image/gif', 'image/webp',
        'audio/mpeg', 'audio/wav', 'audio/mp3',
        'video/mp4', 'video/avi', 'video/mov',
        'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/plain'
      ];

      if (!allowedTypes.includes(file.type)) {
        message.error('不支持的文件类型');
        return false;
      }

      setFileList([file]);
      
      // 根据文件类型自动设置使用类型
      if (file.type.startsWith('image/')) {
        form.setFieldsValue({ usage_type: 'other' });
      } else if (file.type.startsWith('audio/')) {
        form.setFieldsValue({ usage_type: 'audio' });
      } else if (file.type.startsWith('video/')) {
        form.setFieldsValue({ usage_type: 'video' });
      } else {
        form.setFieldsValue({ usage_type: 'document' });
      }

      return false; // 阻止自动上传
    },
    onRemove: () => {
      setFileList([]);
    },
  };

  const handleCancel = () => {
    if (uploading) {
      Modal.confirm({
        title: '确认取消',
        content: '文件正在上传中，确定要取消吗？',
        onOk: () => {
          setUploading(false);
          setUploadProgress(0);
          setFileList([]);
          form.resetFields();
          onCancel();
        },
      });
    } else {
      setFileList([]);
      form.resetFields();
      onCancel();
    }
  };

  return (
    <Modal
      title="上传文件"
      open={visible}
      onCancel={handleCancel}
      onOk={handleUpload}
      confirmLoading={uploading}
      width={600}
      destroyOnClose
      maskClosable={!uploading}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          usage_type: 'other',
        }}
      >
        {/* 文件上传区域 */}
        <Form.Item label="选择文件">
          <Dragger {...uploadProps} style={{ marginBottom: 16 }}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p className="ant-upload-hint">
              支持图片、音频、视频、文档等格式，单个文件不超过50MB
            </p>
          </Dragger>
        </Form.Item>

        {/* 使用类型 */}
        <Form.Item
          name="usage_type"
          label="使用类型"
          rules={[{ required: true, message: '请选择使用类型' }]}
        >
          <Select placeholder="请选择文件使用类型">
            <Select.Option value="avatar">头像</Select.Option>
            <Select.Option value="course_cover">课程封面</Select.Option>
            <Select.Option value="banner">轮播图</Select.Option>
            <Select.Option value="audio">音频文件</Select.Option>
            <Select.Option value="video">视频文件</Select.Option>
            <Select.Option value="document">文档文件</Select.Option>
            <Select.Option value="other">其他</Select.Option>
          </Select>
        </Form.Item>

        {/* 文件描述 */}
        <Form.Item
          name="description"
          label="文件描述"
        >
          <TextArea
            rows={3}
            placeholder="请输入文件描述（可选）"
            maxLength={200}
            showCount
          />
        </Form.Item>

        {/* 上传进度 */}
        {uploading && (
          <div style={{ marginTop: 16 }}>
            <div style={{ marginBottom: 8 }}>上传进度：</div>
            <Progress 
              percent={uploadProgress} 
              status={uploadProgress === 100 ? 'success' : 'active'}
            />
          </div>
        )}

        {/* 上传说明 */}
        <Alert
          message="上传说明"
          description={
            <ul style={{ margin: 0, paddingLeft: 20 }}>
              <li>支持的图片格式：JPEG、PNG、GIF、WebP</li>
              <li>支持的音频格式：MP3、WAV</li>
              <li>支持的视频格式：MP4、AVI、MOV</li>
              <li>支持的文档格式：PDF、Word、Excel、TXT</li>
              <li>单个文件大小不能超过50MB</li>
              <li>上传的文件将自动进行安全检查</li>
            </ul>
          }
          type="info"
          showIcon
          style={{ marginTop: 16 }}
        />
      </Form>
    </Modal>
  );
};

export default FileUploadModal;
